package com.bank1.controller;

import com.bank1.config.RabbitMQConfig;
import com.bank1.domain.User;
import com.bank1.mapper.User1Mapper;
import com.bank2.service.Bank2Interface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/user")
public class User1Controller {
    @Autowired
    private User1Mapper user1Mapper;

    @DubboReference
    private Bank2Interface bank2Service;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;





    @GetMapping("/add")
    public String add(String name,int account){
        user1Mapper.insert(new User(name, account));
        return "添加成功";//直接返回了，没有判断
    }
    @GetMapping("/byName")
    public String add(String name){
        if(StringUtils.isEmpty(name)){
            throw new RuntimeException("查询name不得为空");
        }
        User user = user1Mapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getName, name));
        if(user==null)
            return "查询无果";
        return user.getName()+":"+user.getAmount();
    }


    @GetMapping("/transfer")
    @GlobalTransactional
    public String transfer(String from,int amount,String to) throws InterruptedException {
        //默认参数不为空，不在校验
        //from账户减少金额
        User user = user1Mapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getName, from));
        user.setAmount(user.getAmount()-amount);
        user1Mapper.update(user,new LambdaQueryWrapper<User>().eq(User::getName, from));
        //to账户添加金额
        bank2Service.addAmount(to,amount);
        return "转账成功";
    }

    @GetMapping("/writeRedis")
    public String writeRedis(String msg){
        stringRedisTemplate.opsForValue().append("msg",msg);
        return stringRedisTemplate.opsForValue().get("msg");
    }
    @PostMapping("addScore")
    public void addScore(@RequestBody List<User>list){
        for (User user : list) {
            stringRedisTemplate.opsForZSet().add("list",user.getName(),user.getAmount());
        }
    }

    @GetMapping("/getList")
    public Set<ZSetOperations.TypedTuple<String>> getLeaderboard() {
        return stringRedisTemplate.opsForZSet().reverseRangeWithScores("list",0,-1);
    }
    @GetMapping("/writeMQ")
    public String writeMQ() {
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "boot.as", "Hello,MQ");
        return "添加成功";
    }

}
